package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.checkutils.CheckInsertResultUtil;
import com.xuecheng.content.model.dto.CourseTeacherResultDto;
import com.xuecheng.content.model.dto.CourseTeacherDto;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.service.CourseTeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * <p>
 * 课程-教师关系表 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseTeacherServiceImpl extends ServiceImpl<CourseTeacherMapper, CourseTeacher> implements CourseTeacherService {

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;
    private static final Pattern MD5_PATTERN = Pattern.compile("/([a-f0-9]{32})\\.[a-z]+$", Pattern.CASE_INSENSITIVE);

    @Override
    public PageResult<CourseTeacherResultDto>  selectCourseTeacher(Long courseId, PageParams pageParams) {
        // 1. 创建分页参数
        Page<CourseTeacher> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());

        // 2. 创建查询条件
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId, courseId);

        // 3. 执行分页查询
        Page<CourseTeacher> courseTeacherPage = courseTeacherMapper.selectPage(page, queryWrapper);

        // 4. 获取总记录数和数据列表
        long total = courseTeacherPage.getTotal();
        List<CourseTeacher> teachers = courseTeacherPage.getRecords();

        // 5. 转换为 DTO 列表
        List<CourseTeacherResultDto> dtoList = teachers.stream()
                .map(teacher -> {
                    CourseTeacherResultDto dto = new CourseTeacherResultDto();
                    BeanUtils.copyProperties(teacher, dto);
                    return dto;
                })
                .collect(Collectors.toList());

        // 6. 构建并返回分页结果
        PageResult<CourseTeacherResultDto> result = new PageResult<>();
        result.setItems(dtoList);
        result.setCounts(total);
        result.setPage(pageParams.getPageNo());
        result.setSize(pageParams.getPageSize());

        return result;
    }

    @Override
    public CourseTeacherResultDto createOrUpdateCourseTeacher(CourseTeacherDto courseTeacherDto) {
        CourseTeacher entity = new CourseTeacher();
        BeanUtils.copyProperties(courseTeacherDto, entity);

        if (courseTeacherDto.getId() == null) {
            entity.setCreateDate(LocalDateTime.now());
            CheckInsertResultUtil.check(courseTeacherMapper.insert(entity),()->new XueChengPlusException("新增失败"));
        } else {
            CheckInsertResultUtil.check(courseTeacherMapper.updateNotEmptyFields(entity),()->new XueChengPlusException("修改失败"));
        }

        return convertToResultDto(entity);
    }

    @Override
    public void deleteCourseTeacher(Long courseId, Long teachId) {
        CheckInsertResultUtil.check(courseTeacherMapper.delete(new LambdaQueryWrapper<CourseTeacher>().eq(CourseTeacher::getCourseId,courseId).eq(CourseTeacher::getId,teachId)),()-> new XueChengPlusException("删除失败"));
    }

    @Override
    public CourseTeacherResultDto getCourseTeacherById(Long teacherId) {
        CourseTeacherResultDto courseTeacherResultDto = new CourseTeacherResultDto();
        Optional.ofNullable(teacherId).ifPresent(item ->{
            CourseTeacher selectCourseTeacher = courseTeacherMapper.selectById(teacherId);
            BeanUtils.copyProperties(selectCourseTeacher,courseTeacherResultDto);
        });
        return courseTeacherResultDto;
    }

    private CourseTeacherResultDto convertToResultDto(CourseTeacher entity) {
        CourseTeacherResultDto dto = new CourseTeacherResultDto();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    @Override
    public Map<String, String> courseTeacherIdExtractMd5(Long teacherId) {
        Map<String, String> deleteImageMap = new HashMap<>();
        CourseTeacher selectCourseTeacher = courseTeacherMapper.selectById(teacherId);
        String picUrl = selectCourseTeacher.getPhotograph();
        String md5 = Optional.ofNullable(picUrl)
                .flatMap(this::extractMd5)
                .orElseGet(() -> {
                    log.warn("无法从URL提取MD5: {}", picUrl);
                    return "invalid-md5";
                });
        deleteImageMap.put("md5",md5);
        deleteImageMap.put("url",picUrl);
        return deleteImageMap;
    }

    @Override
    public Boolean updateCourseTeacherPicture(Long teacherId, String picUrl) {
        boolean flag =true;
        CourseTeacher courseTeacherInsert = new CourseTeacher();
        courseTeacherInsert.setId(teacherId);
        courseTeacherInsert.setPhotograph(picUrl);
        int i = courseTeacherMapper.updateNotEmptyFields(courseTeacherInsert);
        if(i<=0){
            flag=false;
        }
        return flag;
    }

    @Override
    public CourseTeacher selectByCourseId(String courseId) {
        return courseTeacherMapper.selectOne(new LambdaQueryWrapper<CourseTeacher>().eq(CourseTeacher::getCourseId,courseId));
    }

    //    url 提取 md5
    public Optional<String> extractMd5(String url) {
        return Optional.ofNullable(url)
                .map(java.net.URI::create)
                .map(java.net.URI::getPath)
                .map(path -> {
                    Matcher matcher = MD5_PATTERN.matcher(path.toLowerCase());
                    return matcher.find() ? matcher.group(1) : null;
                });
    }

}
